package com.gill.demo;

import lombok.Data;
import org.apache.zookeeper.*;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

/**
 *
 * @Description: zookeeper 同步异步修改zk节点demo演示
 */
@Data
public class ZKNodeModify implements Watcher {

    private ZooKeeper zookeeper = null;

    public static final String zkServerPath = "env:2181";
    public static final Integer timeout = 5000;

    public ZKNodeModify() {}

    public ZKNodeModify(String connectString) {
        try {
            zookeeper = new ZooKeeper(connectString, timeout, new ZKNodeModify());
        } catch (IOException e) {
            e.printStackTrace();
            if (zookeeper != null) {
                try {
                    zookeeper.close();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    @Override
    public void process(WatchedEvent event) {
        // 连接成功后，连接时间触发，本次测试不做处理，所以采用空实现
    }

    public static void main(String[] args) throws Exception {
        // 建立连接，创建客户端
        ZKNodeModify zkServer = new ZKNodeModify(zkServerPath);

        /**
         * 参数：
         * path：节点路径
         * data：数据
         * version：数据状态，修改数据之前必须要到zk服务器查看节点的版本，版本不同会报错
         */
        // 1、同步修改
//        Stat status  = zkServer.getZookeeper().setData("/testnode", "modify".getBytes(), 0);
//        System.out.println(status.getVersion());//打印修改之后的版本

        // 2、异步修改
        String ctx = "modify:success";
        zkServer.getZookeeper().setData("/testnode","new-modify".getBytes(),1,new ModifyCallBack(),ctx);
        Thread.sleep(2000);//让回调函数有时间执行
    }

    /**
     * 修改节点成功后，会自动获取节点的一些信息，执行processResult方法
     */
    static class ModifyCallBack implements AsyncCallback.StatCallback {

        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {//Stat是封装了zk每个节点的信息
            System.out.println("修改节点: " + path);
            System.out.println((String)ctx);
        }
    }
}

